<script setup lang="ts">
import type { IOrg, ITreeNode, POrgLoad } from '@/types/bo/OrgBo';
import { ElMessage, ElMessageBox } from 'element-plus-cisdi';
import { debounce } from 'lodash-es';
import { ref, watch } from 'vue';
import Empty from '@/components/empty/index.vue';
import { COUNTRY_TYPE, ORG_TYPE } from '@/constants/Organization.ts';
import { t } from '@/locales';
import { getElementPlusLocales } from '@/locales/ElementPlusCisdi';
import { FormToken } from '@/locales/model/Org';
import * as OrgService from '@/services/OrgService';
import { formatTimestampToLocalDateString } from '@/utils/TimeFormatUtil.ts';
import ListMarker from './components/ListMarker.vue';
import OrgEmpty from './components/OrgEmpty.vue';
import OrgSelect from './components/OrgSelect.vue';

defineOptions({
  name: 'Organization',
});

const locales = getElementPlusLocales();
const orgForm = ref();
const inputRef = ref();
const orgTreeRef = ref();
const searchResult = ref<IOrg[]>([]);
const bizList = ref<IOrg[]>([]);
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref(0);
const version = ref(0);
const actionType = ref<'Create' | 'Update'>('Update');
const fold = ref(true);
const searchInput = ref('');
const requiredField = ref({
  isVirtualDept: false,
  regType: false,
  country: true,
  province: false,
  city: false,
  town: true,
  regAddress: true,
  equityType: false,
});
const orgData = ref<any>({ orgType: '' });
const editable = ref(false);
const tableLoading = ref(false);
const saving = ref(false);
const formLoading = ref(false);
const searching = ref(false);
const treeLoading = ref(false);
const treeProps = {
  children: 'children',
  isLeaf: 'isLeaf',
};
const activeNode = ref<POrgLoad>({ code: '' });
// 宏任务锁，保护details接口初始化数据
const locked = ref<boolean>(false);
const expandedKeys = ref<string []>([]);
function getOrgDetails(params: POrgLoad) {
  if (editable.value || !params.orgCode) {
    return;
  }
  formLoading.value = true;
  OrgService.getOrgInfo(params)
    .then(({ data }: { data: any }) => {
      locked.value = true;
      const timer = setTimeout(() => {
        clearTimeout(timer);
        locked.value = false;
      });
      orgData.value = { ...data[0] || {} };
    })
    .catch((e: Error) => {
      ElMessage.error(e.message || t('message.apiError'));
    })
    .finally(() => {
      orgForm.value.clearValidate();
      formLoading.value = false;
    });
}
function getBizList(orgCode: string, page: number = 1, pageSize: number = 10) {
  if (editable.value || !orgCode) {
    return;
  }
  tableLoading.value = true;
  OrgService
    .fetchOrgBizList({
      orgCode,
      page,
      pageSize,
    })
    .then(({ data }) => {
      total.value = Number(data.total);
      bizList.value = data.records;
    })
    .catch((e: any) => {
      ElMessage.error(e.error || e.message || t('message.apiError'));
    })
    .finally(() => {
      tableLoading.value = false;
    });
}
function onSearch() {
  if (!searchInput.value) {
    searching.value = false;
    searchResult.value = [];
    expandedKeys.value = [];
    activeNode.value.code = '';
    version.value += 1;
    return;
  }
  tableLoading.value = true;
  searching.value = true;
  version.value += 1;
  OrgService
    .onOrgLoad({
      orgCode: 'root',
      keyword: searchInput.value,
      isTree: 0,
      loadType: 1,
    })
    .then(({ data }) => {
      if (data) {
        let result: IOrg[] = [];
        for (const key in data) {
          result = result.concat(data[key]);
        }
        searchResult.value = result;
        activeNode.value = { ...result[0] || {} };
      }
    })
    .catch((e: Error) => {
      ElMessage.error(e.message);
    })
    .finally(() => {
      tableLoading.value = false;
    });
}
function handleClear() {
  searching.value = false;
  searchResult.value = [];
  expandedKeys.value = [];
  activeNode.value.code = '';
  version.value += 1;
  inputRef.value && inputRef.value.blur();
}
function onSave() {
  orgForm.value.validate((valid: boolean) => {
    if (valid) {
      saving.value = true;
      (OrgService[`onOrg${actionType.value}`] as (data: any) => Promise<any>)(orgData.value)
        .then((res) => {
          const data = res.data;
          if (!data) {
            throw new Error(res.response.data.message);
          }
          if (actionType.value === 'Create') {
            const parentNode = orgTreeRef.value.getNode(orgData.value.parentCode);
            orgTreeRef.value.append(data, parentNode);
          }
          Object.assign(orgData.value, data);
          editable.value = false;
          actionType.value = 'Update';
          ElMessage.success(t('message.saved'));
        })
        .catch((e: Error) => {
          ElMessage.error(e.message || t('message.saveFail'));
          console.error(e);
        })
        .finally(() => {
          saving.value = false;
        });
    } else if (fold.value) {
      ElMessage.error(t('message.validFail'));
    }
  });
}
function onCancel() {
  const currentNode = orgTreeRef.value.getNode(activeNode.value.parentCode);
  activeNode.value.code = currentNode.data.code;
  activeNode.value.label = currentNode.data.label;
  activeNode.value.parentCode = currentNode.data.parentCode;
  editable.value = false;
}
function onFold() {
  fold.value = !fold.value;
}
function onSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;
  getBizList(orgData.value.code, 1, size);
}
function onPagerChange(pager: number) {
  currentPage.value = pager;
  getBizList(orgData.value.code, pager, pageSize.value);
}
// 当新建扩展组织时，向上追溯非扩展组织的orgCode
function getRealOrgCode(code: string) {
  const node = orgTreeRef.value.getNode(code);
  if (node.data.isExtend) {
    return getRealOrgCode(node.data.parentCode);
  }
  return node.data.code;
}
async function onCreateNode(command: string, data: IOrg, node: any) {
  try {
    let parentCode = data.code;
    if (command === 'parallel') {
      parentCode = data.parentCode;
    }
    const newNode = {
      parentCode,
      orgType: '',
      isExtend: 1,
      isVirtualDept: '0',
      bindOrgCode: getRealOrgCode(parentCode || ''),
    };
    node.expanded = true;
    orgData.value = newNode;
    activeNode.value = newNode;
    editable.value = true;
    fold.value = false;
    actionType.value = 'Create';
  } catch (e: any) {
    ElMessage.error(e.message);
  } finally {
    orgForm.value.resetFields();
  }
}
function onTreeClick(node: IOrg) {
  if (editable.value && node.code !== activeNode.value.code) {
    ElMessageBox.confirm(t('message.giveUpEdit'), t('message.tip'), {
      customClass: 'wk-org__message-box',
      appendTo: '.wk-org',
      cancelButtonText: t('action.cancel'),
      confirmButtonText: t('action.sure'),
      callback: (action: string) => {
        if (action === 'confirm') {
          activeNode.value.code = node.code;
          activeNode.value.label = node.label;
          activeNode.value.parentCode = node.parentCode;
          editable.value = false;
          fold.value = true;
        }
      },
    });
  } else if (!editable.value && node.code !== activeNode.value.code) {
    activeNode.value.code = node.code;
    activeNode.value.label = node.label;
    activeNode.value.parentCode = node.parentCode;
  }
}
function onTreeLoad(node: ITreeNode, resolve: (value?: any) => void) {
  const params = {
    loadType: 0,
    isTree: 0,
    orgCode: '',
  };
  if (node.data && node.data.code) {
    params.orgCode = node.data.code;
  }
  if (!params.orgCode) {
    params.orgCode = 'root';
  }
  treeLoading.value = true;
  OrgService
    .onOrgLoad(params)
    .then(({ data }) => {
      if (data) {
        let result: IOrg[] = [];
        for (const key in data) {
          result = result.concat(data[key]);
        }
        if (!activeNode.value.code && result && result[0]) {
          activeNode.value.code = result[0].code;
        }
        if (activeNode.value.code && expandedKeys.value.length === 0) {
          expandedKeys.value = [activeNode.value.code];
          orgTreeRef.value.setCurrentKey(activeNode.value.code);
        }
        isLeafNodes(result);
        resolve(result);
      }
    })
    .catch((e: Error) => {
      ElMessage.error(e.message);
      treeLoading.value = false;
    });
}
function isLeafNodes(nodes: ITreeNode) {
  for (let i = 0; i < nodes.length; i++) {
    if (!nodes[i].isLeaf) {
      nodes[i].children = [];
    } else {
      nodes[i].isLeaf = true;
      delete nodes[i].children;
    }
  }
}
function highlighted(label: string) {
  const regex = new RegExp(searchInput.value, 'gi');
  return label.replace(regex, (match: string) => `<span class="wk-org__node-highlighted">${match}</span>`);
}
function onClearSelect(fields: string[]) {
  if (!locked.value) {
    for (const field of fields) {
      orgData.value[field] = '';
    }
  }
}
function onRetry() {
  version.value += 1;
}
function onInput(val: string) {
  searchInput.value = val;
  searching.value = true;
}
watch(() => activeNode.value.code, (val, old) => {
  if (val !== old) {
    bizList.value = [];
    getOrgDetails({ orgCode: val });
    getBizList(val || '');
  }
});
watch(() => orgData.value.orgType, (val) => {
  if (val === ORG_TYPE.INNER) {
    // 当组织机构类型是内设机构时，isVirtualDept必填
    requiredField.value.isVirtualDept = true;
    // 当组织机构类型是内设机构时，country非必填
    requiredField.value.country = false;
    requiredField.value.province = false;
    requiredField.value.city = false;
    requiredField.value.town = false;
    orgForm.value.clearValidate(['country']);
  } else {
    requiredField.value.isVirtualDept = false;
    requiredField.value.country = true;
    if (orgData.value.country === COUNTRY_TYPE.CHINA) {
      requiredField.value.province = true;
      requiredField.value.city = true;
      requiredField.value.town = true;
    }
    orgForm.value.clearValidate(['isVirtualDept']);
  }
  // 当组织机构是法人、分公司、事业单位时，注册类型必填
  if ([ORG_TYPE.LEGAL_PERSON, ORG_TYPE.BRANCH_COMPANY, ORG_TYPE.BUSINESS_DIVISION].includes(val)) {
    requiredField.value.equityType = true;
    requiredField.value.regType = true;
  } else {
    requiredField.value.regType = false;
    requiredField.value.equityType = false;
    orgForm.value.clearValidate(['regType']);
  }
});
watch(() => orgData.value.country, (val) => {
  // 当“国家”为“中国，台湾，香港，澳门”时，province必填
  if ([COUNTRY_TYPE.CHINA, COUNTRY_TYPE.TAIWAN, COUNTRY_TYPE.HONGKONG, COUNTRY_TYPE.MACAO].includes(val)) {
    requiredField.value.province = true;
    requiredField.value.regAddress = true;
  } else {
    requiredField.value.province = false;
    requiredField.value.regAddress = false;
    orgForm.value.clearValidate(['province', 'regAddress']);
  }
  // 当“国家”为“中国”时，city必填
  if ([COUNTRY_TYPE.CHINA].includes(val)) {
    requiredField.value.city = true;
    requiredField.value.town = true;
  } else {
    requiredField.value.city = false;
    requiredField.value.town = false;
    orgForm.value.clearValidate(['city', 'town']);
  }
});
watch(() => searchInput.value, debounce(() => {
  onSearch();
}, 500));
</script>

<template>
  <ElConfigProvider :locale="locales">
    <div class="wk-org__wrapper">
      <div class="wk-org">
        <!-- 左侧区域 -->
        <aside
          class="wk-org__aside"
          :class="{
            searching: searchResult && searchResult.length,
          }"
        >
          <ElInput
            ref="inputRef"
            :placeholder="t('org.searchTitle')"
            :model-value="searchInput"
            clearable
            @clear="handleClear"
            @input="onInput"
            @keyup.enter="onSearch"
          >
            <template #suffix>
              <svg
                class="wk-org__tree-search"
                width="13.28753662109375"
                height="13.99346923828125"
                viewBox="0 0 13.28753662109375 13.99346923828125"
                @click="onSearch"
              >
                <path d="M13.018833,12.434334L9.991333,9.3660002C10.831146,8.3368549,11.288365,7.0484796,11.285167,5.7201667C11.285167,2.5608335,8.7581663,0,5.6431665,0C2.5258334,0,0,2.5608335,0,5.7201667C0,8.8783331,2.5258334,11.4415,5.6431665,11.4415C6.7071071,11.442271,7.7489328,11.137781,8.6450005,10.564167L11.754167,13.7165C11.923622,13.893051,12.157622,13.993049,12.402337,13.993488C12.634931,13.993907,12.85817,13.904351,13.02576,13.744409C13.024236,13.745998,13.022704,13.747584,13.021167,13.749166L13.02994,13.740394C13.037235,13.733341,13.044423,13.726153,13.0515,13.718833L13.02994,13.740394C13.02855,13.741737,13.027157,13.743075,13.02576,13.744409C13.37722,13.377804,13.374657,12.797818,13.018833,12.434334ZM5.6422186,9.7486658Q5.837461,9.7486658,6.0317631,9.7292671Q6.2260652,9.7098694,6.4175558,9.6712589Q6.6090469,9.6326494,6.7958822,9.5751991Q6.9827175,9.5177498,7.1630974,9.4420128Q7.3434782,9.3662777,7.515667,9.2729845Q7.6878552,9.1796913,7.850193,9.0697393Q8.0125313,8.9597883,8.163456,8.8342371Q8.3143806,8.7086868,8.4524374,8.5687447Q8.5904951,8.4288034,8.7143555,8.2758188Q8.8382158,8.1228342,8.9466858,7.9582796Q9.0551567,7.793726,9.1471939,7.6191869Q9.2392302,7.4446483,9.3139458,7.2618051Q9.3886623,7.0789628,9.4453382,6.8895774Q9.5020142,6.7001915,9.5401039,6.5060863Q9.5781946,6.3119822,9.597332,6.1150274Q9.6164684,5.9180737,9.6164684,5.7201657Q9.6164684,5.5222588,9.597332,5.325304Q9.5781946,5.1283493,9.5401039,4.9342437Q9.5020142,4.740139,9.4453382,4.5507536Q9.3886623,4.3613682,9.3139458,4.178525Q9.2392302,3.9956827,9.1471939,3.8211439Q9.0551567,3.646605,8.9466858,3.4820507Q8.8382158,3.3174968,8.7143555,3.1645122Q8.5904951,3.0115275,8.4524374,2.8715858Q8.3143806,2.7316442,8.163456,2.6060929Q8.0125313,2.4805417,7.850193,2.3705902Q7.6878552,2.2606387,7.515667,2.1673458Q7.3434782,2.0740528,7.1630974,1.9983168Q6.9827175,1.922581,6.7958822,1.8651315Q6.6090465,1.807682,6.4175553,1.7690721Q6.2260647,1.7304623,6.0317631,1.711064Q5.837461,1.6916656,5.6422186,1.6916656Q5.4469762,1.6916656,5.2526741,1.7110641Q5.0583715,1.7304624,4.8668804,1.7690722Q4.6753902,1.807682,4.488555,1.8651316Q4.3017197,1.922581,4.1213388,1.9983168Q3.9409585,2.0740528,3.7687702,2.1673458Q3.5965817,2.2606387,3.4342434,2.3705902Q3.2719054,2.4805417,3.1209812,2.6060929Q2.9700565,2.7316442,2.8319993,2.8715858Q2.6939421,3.0115275,2.5700817,3.1645122Q2.4462214,3.3174968,2.3377504,3.4820507Q2.2292795,3.646605,2.137243,3.8211436Q2.0452065,3.9956827,1.9704905,4.178525Q1.8957746,4.3613682,1.8390987,4.5507536Q1.7824228,4.740139,1.7443328,4.9342437Q1.706243,5.1283493,1.6871059,5.325304Q1.6679689,5.5222588,1.6679688,5.7201657Q1.6679689,5.9180737,1.6871059,6.1150279Q1.706243,6.3119822,1.7443328,6.5060863Q1.7824228,6.7001915,1.8390987,6.8895769Q1.8957745,7.0789628,1.9704903,7.2618051Q2.0452065,7.4446483,2.137243,7.6191874Q2.2292795,7.793726,2.3377504,7.9582796Q2.4462214,8.1228342,2.5700817,8.2758188Q2.6939421,8.4288034,2.8319993,8.5687447Q2.9700565,8.7086868,3.120981,8.8342371Q3.2719054,8.9597893,3.4342432,9.0697403Q3.5965815,9.1796913,3.76877,9.2729845Q3.9409585,9.3662777,4.1213388,9.4420128Q4.3017197,9.5177498,4.488555,9.5751991Q4.6753902,9.6326494,4.8668804,9.6712589Q5.0583715,9.7098694,5.2526741,9.7292671Q5.4469762,9.7486658,5.6422186,9.7486658Z" fill-rule="evenodd" fill="#222222" fill-opacity="0.550000011920929" />
              </svg>
            </template>
          </ElInput>
          <div class="wk-org__tree__wrapper">
            <ElTree
              ref="orgTreeRef"
              :key="version"
              node-key="code"
              :lazy="!searching"
              :data="searchResult"
              :load="onTreeLoad"
              :props="treeProps"
              :highlight-current="true"
              :expand-on-click-node="false"
              :default-expanded-keys="expandedKeys"
              @node-click="onTreeClick"
            >
              <template #default="{ data, node }">
                <div class="wk-org__tree-node">
                  <span class="wk-org__tree-label">
                    <span v-if="searchInput" v-html="highlighted(data.label)" />
                    <template v-else>
                      {{ data.label }}
                    </template>
                    <span
                      v-if="data.isExtend"
                      class="wk-org__tree-tag"
                    >
                      {{ t('message.tag') }}
                    </span>
                  </span>
                  <div
                    v-if="!searchInput"
                    class="wk-org__create-node"
                  >
                    <ElDropdown @command="(command:any) => onCreateNode(command, data, node)">
                      <span class="el-dropdown-link">
                        <svg fill="none" version="1.1" width="22" height="22" viewBox="0 0 22 22">
                          <g>
                            <g transform="matrix(0,1,-1,0,22,-22)" />
                            <g>
                              <g transform="matrix(0,1,-1,0,15.125,-9.625)">
                                <path d="M15.125,4.125Q15.125,4.1925495,15.1183791,4.2597735Q15.111758,4.3269976,15.0985794,4.393249Q15.0854015,4.4595006,15.065793,4.5241412Q15.0461843,4.5887818,15.020334,4.6511893Q14.9944842,4.7135967999999995,14.962641699999999,4.7731702Q14.930799,4.8327434,14.8932705,4.888908600000001Q14.855742,4.945074099999999,14.8128891,4.9972904Q14.7700362,5.0495067,14.7222717,5.0972714Q14.6745071,5.1450362,14.6222906,5.1878891Q14.5700741,5.230741999999999,14.5139089,5.2682705Q14.4577436,5.305799,14.398170499999999,5.3376415Q14.3385971,5.3694839000000005,14.2761894,5.395334Q14.2137821,5.4211843,14.1491413,5.4407928000000005Q14.0845006,5.4604015,14.018249,5.4735794Q13.9519976,5.486758,13.8847735,5.4933791Q13.8175495,5.5,13.75,5.5Q13.6824505,5.5,13.615226400000001,5.4933791Q13.548002199999999,5.486758,13.4817507,5.4735794Q13.4154993,5.4604015,13.35085857,5.440793Q13.28621781,5.4211843,13.223810199999999,5.395334Q13.1614027,5.3694842000000005,13.10182947,5.3376417Q13.04225624,5.305799,12.9860909,5.2682705Q12.92992562,5.230741999999999,12.87770921,5.1878891Q12.8254928,5.1450362,12.77772814,5.0972717Q12.72996351,5.0495071,12.6871106,4.9972905999999995Q12.64425769,4.945074099999999,12.60672924,4.888908900000001Q12.56920081,4.832743600000001,12.53735824,4.7731705Q12.50551566,4.7135971,12.47966562,4.6511894Q12.453815587,4.5887820999999995,12.43420703,4.5241413Q12.414598472,4.4595006,12.401420234,4.393249Q12.388242,4.3269976,12.3816209999,4.2597735Q12.375,4.1925495,12.375,4.125Q12.375,4.0574505,12.3816209999,3.9902264Q12.388242,3.9230022,12.401420234,3.8567507Q12.414598472,3.7904993,12.43420703,3.7258585699999998Q12.453815587,3.66121781,12.47966562,3.5988102Q12.50551566,3.5364027,12.53735824,3.47682947Q12.56920081,3.41725624,12.60672924,3.3610908999999998Q12.64425769,3.30492562,12.6871106,3.25270921Q12.72996351,3.2004928,12.77772814,3.15272814Q12.8254928,3.10496351,12.87770921,3.0621106Q12.92992562,3.01925769,12.9860909,2.98172924Q13.04225624,2.94420081,13.10182941,2.91235824Q13.1614027,2.88051566,13.223810199999999,2.85466562Q13.28621781,2.828815587,13.35085857,2.80920703Q13.4154993,2.789598472,13.4817507,2.776420234Q13.548002199999999,2.763242,13.6152265,2.7566209999Q13.6824505,2.75,13.75,2.75Q13.8175495,2.75,13.8847735,2.7566209999Q13.9519976,2.763242,14.018249,2.776420234Q14.0845006,2.789598472,14.1491412,2.80920703Q14.2137818,2.828815587,14.2761893,2.85466562Q14.3385968,2.88051566,14.3981702,2.91235824Q14.4577434,2.94420081,14.5139086,2.98172924Q14.5700741,3.01925769,14.6222904,3.0621106Q14.6745067,3.10496351,14.7222714,3.15272814Q14.7700362,3.2004928,14.8128891,3.25270921Q14.855742,3.30492562,14.8932705,3.3610908999999998Q14.930799,3.41725624,14.9626415,3.47682941Q14.9944839,3.5364027,15.020334,3.5988102Q15.0461843,3.66121781,15.0657928,3.7258585699999998Q15.0854015,3.7904993,15.0985794,3.8567507Q15.111758,3.9230022,15.1183791,3.9902265Q15.125,4.0574505,15.125,4.125Z" fill="#222222" fill-opacity="0.75" /></g><g transform="matrix(0,1,-1,0,22,-2.75)"><path d="M15.125,11Q15.125,11.0675495,15.1183791,11.1347735Q15.111758,11.2019976,15.0985794,11.268249Q15.0854015,11.3345006,15.065793,11.3991412Q15.0461843,11.4637818,15.020334,11.5261893Q14.9944842,11.5885968,14.962641699999999,11.6481702Q14.930799,11.7077434,14.8932705,11.7639086Q14.855742,11.8200741,14.8128891,11.8722904Q14.7700362,11.9245067,14.7222717,11.9722714Q14.6745071,12.0200362,14.6222906,12.0628891Q14.5700741,12.105742,14.5139089,12.1432705Q14.4577436,12.180799,14.398170499999999,12.2126415Q14.3385971,12.2444839,14.2761894,12.270334Q14.2137821,12.2961843,14.1491413,12.3157928Q14.0845006,12.3354015,14.018249,12.3485794Q13.9519976,12.361758,13.8847735,12.3683791Q13.8175495,12.375,13.75,12.375Q13.6824505,12.375,13.615226400000001,12.3683791Q13.548002199999999,12.361758,13.4817507,12.3485794Q13.4154993,12.3354015,13.35085857,12.315793Q13.28621781,12.2961843,13.223810199999999,12.270334Q13.1614027,12.2444842,13.10182947,12.212641699999999Q13.04225624,12.180799,12.9860909,12.1432705Q12.92992562,12.105742,12.87770921,12.0628891Q12.8254928,12.0200362,12.77772814,11.9722717Q12.72996351,11.9245071,12.6871106,11.8722906Q12.64425769,11.8200741,12.60672924,11.7639089Q12.56920081,11.7077436,12.53735824,11.648170499999999Q12.50551566,11.5885971,12.47966562,11.5261894Q12.453815587,11.4637821,12.43420703,11.3991413Q12.414598472,11.3345006,12.401420234,11.268249Q12.388242,11.2019976,12.3816209999,11.1347735Q12.375,11.0675495,12.375,11Q12.375,10.9324505,12.3816209999,10.865226400000001Q12.388242,10.798002199999999,12.401420234,10.7317507Q12.414598472,10.6654993,12.43420703,10.60085857Q12.453815587,10.53621781,12.47966562,10.473810199999999Q12.50551566,10.4114027,12.53735824,10.35182947Q12.56920081,10.29225624,12.60672924,10.2360909Q12.64425769,10.17992562,12.6871106,10.12770921Q12.72996351,10.0754928,12.77772814,10.02772814Q12.8254928,9.97996351,12.87770921,9.9371106Q12.92992562,9.89425769,12.9860909,9.85672924Q13.04225624,9.81920081,13.10182941,9.78735824Q13.1614027,9.75551566,13.223810199999999,9.72966562Q13.28621781,9.703815587,13.35085857,9.68420703Q13.4154993,9.664598472,13.4817507,9.651420234Q13.548002199999999,9.638242,13.6152265,9.6316209999Q13.6824505,9.625,13.75,9.625Q13.8175495,9.625,13.8847735,9.6316209999Q13.9519976,9.638242,14.018249,9.651420234Q14.0845006,9.664598472,14.1491412,9.68420703Q14.2137818,9.703815587,14.2761893,9.72966562Q14.3385968,9.75551566,14.3981702,9.78735824Q14.4577434,9.81920081,14.5139086,9.85672924Q14.5700741,9.89425769,14.6222904,9.9371106Q14.6745067,9.97996351,14.7222714,10.02772814Q14.7700362,10.0754928,14.8128891,10.12770921Q14.855742,10.17992562,14.8932705,10.2360909Q14.930799,10.29225624,14.9626415,10.35182941Q14.9944839,10.4114027,15.020334,10.473810199999999Q15.0461843,10.53621781,15.0657928,10.60085857Q15.0854015,10.6654993,15.0985794,10.7317507Q15.111758,10.798002199999999,15.1183791,10.8652265Q15.125,10.9324505,15.125,11Z" fill="#222222" fill-opacity="0.75" />
                                </g>
                              <g transform="matrix(0,1,-1,0,28.875,4.125)">
                                <path d="M15.125,17.875Q15.125,17.9425495,15.1183791,18.0097735Q15.111758,18.0769976,15.0985794,18.143249Q15.0854015,18.2095006,15.065793,18.2741412Q15.0461843,18.3387818,15.020334,18.4011893Q14.9944842,18.4635968,14.962641699999999,18.5231702Q14.930799,18.5827434,14.8932705,18.6389086Q14.855742,18.6950741,14.8128891,18.7472904Q14.7700362,18.7995067,14.7222717,18.8472714Q14.6745071,18.8950362,14.6222906,18.9378891Q14.5700741,18.980742,14.5139089,19.0182705Q14.4577436,19.055799,14.398170499999999,19.0876415Q14.3385971,19.1194839,14.2761894,19.145334Q14.2137821,19.1711843,14.1491413,19.1907928Q14.0845006,19.2104015,14.018249,19.2235794Q13.9519976,19.236758000000002,13.8847735,19.2433791Q13.8175495,19.25,13.75,19.25Q13.6824505,19.25,13.615226400000001,19.2433791Q13.548002199999999,19.236758000000002,13.4817507,19.2235794Q13.4154993,19.2104015,13.35085857,19.190793Q13.28621781,19.1711843,13.223810199999999,19.145334Q13.1614027,19.1194842,13.10182947,19.0876417Q13.04225624,19.055799,12.9860909,19.0182705Q12.92992562,18.980742,12.87770921,18.9378891Q12.8254928,18.8950362,12.77772814,18.8472717Q12.72996351,18.7995071,12.6871106,18.7472906Q12.64425769,18.6950741,12.60672924,18.6389089Q12.56920081,18.5827436,12.53735824,18.5231705Q12.50551566,18.4635971,12.47966562,18.4011894Q12.453815587,18.3387821,12.43420703,18.2741413Q12.414598472,18.2095006,12.401420234,18.143249Q12.388242,18.0769976,12.3816209999,18.0097735Q12.375,17.9425495,12.375,17.875Q12.375,17.8074505,12.3816209999,17.7402264Q12.388242,17.6730022,12.401420234,17.6067507Q12.414598472,17.5404993,12.43420703,17.47585857Q12.453815587,17.41121781,12.47966562,17.3488102Q12.50551566,17.2864027,12.53735824,17.22682947Q12.56920081,17.16725624,12.60672924,17.1110909Q12.64425769,17.05492562,12.6871106,17.00270921Q12.72996351,16.9504928,12.77772814,16.90272814Q12.8254928,16.85496351,12.87770921,16.8121106Q12.92992562,16.76925769,12.9860909,16.73172924Q13.04225624,16.69420081,13.10182941,16.66235824Q13.1614027,16.63051566,13.223810199999999,16.60466562Q13.28621781,16.578815587,13.35085857,16.55920703Q13.4154993,16.539598472,13.4817507,16.526420234Q13.548002199999999,16.513242,13.6152265,16.5066209999Q13.6824505,16.5,13.75,16.5Q13.8175495,16.5,13.8847735,16.5066209999Q13.9519976,16.513242,14.018249,16.526420234Q14.0845006,16.539598472,14.1491412,16.55920703Q14.2137818,16.578815587,14.2761893,16.60466562Q14.3385968,16.63051566,14.3981702,16.66235824Q14.4577434,16.69420081,14.5139086,16.73172924Q14.5700741,16.76925769,14.6222904,16.8121106Q14.6745067,16.85496351,14.7222714,16.90272814Q14.7700362,16.9504928,14.8128891,17.00270921Q14.855742,17.05492562,14.8932705,17.1110909Q14.930799,17.16725624,14.9626415,17.22682941Q14.9944839,17.2864027,15.020334,17.3488102Q15.0461843,17.41121781,15.0657928,17.47585857Q15.0854015,17.5404993,15.0985794,17.6067507Q15.111758,17.6730022,15.1183791,17.7402265Q15.125,17.8074505,15.125,17.875Z" fill="#222222" fill-opacity="0.75" />
                              </g>
                            </g>
                          </g>
                        </svg>
                      </span>
                      <template #dropdown>
                        <ElDropdownMenu>
                          <ElDropdownItem
                            v-if="data.parentCode"
                            command="parallel"
                          >
                            {{ t('action.createParallel') }}
                          </ElDropdownItem>
                          <ElDropdownItem command="next">
                            {{ t('action.createNext') }}
                          </ElDropdownItem>
                        </ElDropdownMenu>
                      </template>
                    </ElDropdown>
                  </div>
                </div>
              </template>
              <template #empty>
                <OrgEmpty v-if="!treeLoading" @retry="onRetry" />
              </template>
            </ElTree>
          </div>
        </aside>
        <!-- 右侧区域 -->
        <div class="right-content">
          <div style="overflow-y: auto;" class="form-and-table-wrapper">
            <div class="wk-org__header">
              <h1 class="wk-org__active-node">
                {{ activeNode.label || orgData.orgShortName }}
                <ElButton
                  v-if="editable"
                  class="wk-org__active-node-cancel"
                  @click="onCancel"
                >
                  {{ t('action.cancel') }}
                </ElButton>
                <ElButton v-if="orgData && orgData.isExtend" class="wk-org__active-node-save" :disabled="saving" @click="onSave">
                  {{ t('action.save') }}
                </ElButton>
              </h1>
            </div>
            <main class="wk-org__main">
              <h1 class="wk-org__subtitle">
                {{ t('org.subTitle') }}
                <svg
                  class="wk-org__fold"
                  :class="{
                    active: fold,
                  }"
                  version="1.1"
                  width="11"
                  height="6"
                  viewBox="0 0 11 6"
                  @click="onFold"
                >
                  <g transform="matrix(1,5.2146120310681e-8,-5.2146120310681e-8,1,0,-1.7723595277053013e-14)">
                    <path d="M5.148931339883297,0.19780026L0.14484917988329662,5.2007155C-0.07188392711670338,5.491065,-0.04254873711670338,5.8965101,0.2137235698832966,6.1526356C0.46999583988329663,6.4087615,0.8754570898832966,6.4378648,1.1656825398832966,6.2209659L5.658181539883296,1.7284669L10.150681339883297,6.2209659C10.320005339883297,6.4509954,10.608047339883296,6.5609794,10.887593339883297,6.5023441C11.167140339883296,6.4437099,11.386710339883297,6.2272544,11.449334339883297,5.9485741C11.511956339883296,5.6698937,11.406099339883296,5.3803105,11.178514339883296,5.207716L6.168598039883297,0.19780026C5.8879455398832965,-0.065933421,5.450584239883296,-0.065933421,5.169931739883297,0.19780026L5.148931339883297,0.19780026Z" fill="#222222" fill-opacity="0.550000011920929" />
                  </g>
                </svg>
              </h1>
              <ElForm
                ref="orgForm"
                v-loading="formLoading"
                :model="orgData"
                label-width="109px"
                label-position="top"
              >
                <template
                  v-for="legend in ['basic', 'code', 'geo', 'reg', 'mgmt', 'hr', 'shareholder']"
                  :key="legend"
                >
                  <fieldset
                    v-show="legend === 'basic' || !fold"
                    class="wk-org-panel"
                  >
                    <legend v-if="legend !== 'basic'" class="wk-org__legend">
                      <ListMarker />
                      {{ t(`org.${legend}Title`) }}
                    </legend>
                    <div class="wk-org__form-items">
                      <template v-if="FormToken.org[`${legend}Info`]">
                        <ElFormItem
                          v-for="([field], index) in Object.entries(FormToken.org[`${legend}Info`])"
                          :key="field"
                          :prop="field"
                          :rules="FormToken.org[`${legend}Info`][field].rules"
                          :required="requiredField[field as keyof typeof requiredField] || FormToken.org[`${legend}Info`][field].required"
                          :class="{
                            [field]: true,
                            'left-item': index % 3 === 0,
                            'center-item': index % 3 === 1,
                            'right-item': index % 3 === 2,
                            'plus-item': field === 'reg_address',
                          }"
                          class="wk-org__form-item"
                        >
                          <template #label>
                            <span :title="t(`org.${legend}Info.${field}.label`)">
                              {{ t(`org.${legend}Info.${field}.label`) }}
                            </span>
                          </template>
                          <OrgSelect
                            v-if="FormToken.org[`${legend}Info`][field].renderer === 'select'"
                            v-model="orgData[field as keyof typeof orgData]"
                            :options="FormToken.org[`${legend}Info`][field].options"
                            :name="field"
                            :url="FormToken.org[`${legend}Info`][field].tableName"
                            :params="FormToken.org[`${legend}Info`][field].params"
                            :form-data="orgData"
                            :placeholder="`${t('message.select')}${t(`org.${legend}Info.${field}.label`)}`"
                            :clearable="true"
                            :disabled="!orgData.isExtend"
                            @clear="onClearSelect"
                          />
                          <ElRadioGroup
                            v-else-if="FormToken.org[`${legend}Info`][field].renderer === 'radio'"
                            v-model="orgData[field as keyof typeof orgData]"
                            :disabled="FormToken.org[`${legend}Info`][field].disabled || !orgData.isExtend"
                          >
                            <ElRadio
                              v-for="item in FormToken.org[`${legend}Info`][field].options"
                              :key="item.value"
                              :value="item.value"
                            >
                              {{ item.label }}
                            </ElRadio>
                          </ElRadioGroup>
                          <ElInput
                            v-else
                            v-model="orgData[field as keyof typeof orgData]"
                            :disabled="!orgData.isExtend"
                            :placeholder="`${t('message.input')}${t(`org.${legend}Info.${field}.label`)}`"
                            clearable
                          />
                          <template #error="{ error }">
                            <div class="el-form-item__error">
                              {{ typeof error === 'string' && error.includes('is required') ? FormToken.org[`${legend}Info`][field].options ? t('message.select') : t('message.input') : error }}
                            </div>
                          </template>
                        </ElFormItem>
                      </template>
                    </div>
                  </fieldset>
                </template>
              </ElForm>
            </main>
            <div
              v-if="!editable"
              class="wk-org__bottom"
            >
              <div style="flex: 1; display: flex; flex-direction: column;">
                <h1 class="wk-org__subtitle" style="height: 47px;">
                  {{ t('org.bizTitle') }}
                </h1>
                <ElTable
                  v-if="!editable"
                  v-loading="tableLoading"
                  :resizable="true"
                  :border="true"
                  :data="bizList"
                  class="wk-org-biz__table"
                >
                  <el-table-column
                    type="index"
                    width="50"
                    :label="t('message.index')"
                  />
                  <ElTableColumn
                    v-for="column in Object.keys(FormToken.biz)"
                    :key="column"
                    :prop="column"
                    :label="t(`biz.${column}.label`)"
                    :min-width="FormToken.biz[column].width"
                    show-overflow-tooltip
                  >
                    <template #default="scope">
                      <OrgSelect
                        v-if="FormToken.biz[column].renderer === 'OrgSelect'"
                        :params="FormToken.biz[column].params"
                        :url="FormToken.biz[column].tableName"
                        :model-value="scope.row[column]"
                        :form-data="orgData"
                        :is-static="true"
                      />
                    </template>
                  </ElTableColumn>

                  <ElTableColumn prop="createName" :label="t('common.createBy')" min-width="120" />
                  <ElTableColumn prop="createTime" :label="t('common.createTime')" min-width="180">
                    <template #default="{ row }">
                      <span>{{ row.createTime === null ? '-' : formatTimestampToLocalDateString(row.createTime) }}</span>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn prop="updateName" :label="t('common.updateBy')" min-width="120" />
                  <ElTableColumn prop="updateTime" :label="t('common.updateTime')" min-width="180">
                    <template #default="{ row }">
                      <span>{{ row.updateTime === null ? '-' : formatTimestampToLocalDateString(row.updateTime) }}</span>
                    </template>
                  </ElTableColumn>

                  <ElTableColumn
                    :label="t('action.actions')"
                    fixed="right"
                    width="120"
                  >
                    <template #default="scope = {}">
                      <ElLink
                        :href="scope.row?.path"
                        target="_blank"
                        type="primary"
                      >
                        {{ t('action.details') }}
                      </ElLink>
                    </template>
                  </ElTableColumn>
                  <template #empty>
                    <Empty />
                  </template>
                </ElTable>
              </div>
              <ElPagination
                v-if="!editable"
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                class="wk-org-biz__pagination"
                @size-change="onSizeChange"
                @current-change="onPagerChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </ElConfigProvider>
</template>

<style scoped lang="scss">
@use './organization.scss' as *;
</style>
